from flask import current_app, jsonify
from flask import g
from flask import session
from werkzeug.routing import BaseConverter
import functools

from ihome.utils.response_code import RET


class RegexConverter(BaseConverter):
    """自定义的正则转换器"""

    def __init__(self, url_map, *args):
        super(RegexConverter, self).__init__(url_map)
        self.regex = args[0]


def get_user_info(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        user_id = session.get("user_id")
        from ihome.models import User
        user = None  # type: User
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
        g.user = user
        result = view_func(*args, **kwargs)
        return result
    return wrapper

